package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @作者 itcast
 * @创建日期 2021/4/12 9:53
 **/
@Service
//@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        // 1. 检查参数
        dto.checkParam();
        // 2. 执行查询
        // 2.1  封装分页条件
        Page<ApUserRealname> pageReq = new Page<>(dto.getPage(), dto.getSize());
        // 2.2  查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if(dto.getStatus()!=null){
            queryWrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(pageReq, queryWrapper);
        // 3. 返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        pageResponseResult.setData(pageResult.getRecords());
        return pageResponseResult;
    }

    @Autowired
    ApUserMapper apUserMapper;
    /**
     * 根据状态进行审核
     * @param dto
     * @param status  2 审核失败   9 审核成功
     * @return
     */
    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDto dto, Short status) {
        // 检查参数 ( dto.id 必须存在 )
        if(dto == null || dto.getId() == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"实名认证id不存在");
        }
        // 根据dto.id查询ap_user_realname数据
        ApUserRealname userRealname = getById(dto.getId());
        // 判断实名认证状态 (状态必须为待审核状态 == 1 )
        if(userRealname == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证数据不存在");
        }
        if(userRealname.getStatus().intValue()!=1){
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR,"实名认证状态错误");
        }
        // 查询ap_user信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if(apUser == null){
            throw new CustomException(AppHttpCodeEnum.DATA_STATUS_ERROR,"关联的app用户信息不存在");
        }
        // 修改实名认证状态 ap_user_realname
        userRealname.setStatus(status);
        userRealname.setUpdatedTime(new Date());
        if(StringUtils.isNotBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());//原因
        }
        updateById(userRealname);
        // 如果是认证通过的情况下:
        if(status.intValue() == AdminConstants.AD_USER_ISSTATUS){// 通过的情况
            //    开通自媒体账户 (基于ApUser ==> 创建WmUser)
            WmUser wmUser = createWmUser(apUser);
            if(wmUser == null){
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"自媒体账户创建失败");
            }
            //    创建作者信息  (基于ApUser WmUser ==> 创建ApAuthor)
            ResponseResult result = createAuthor(apUser,wmUser);
            if(result.getCode() != 0){
                throw new CustomException(AppHttpCodeEnum.SERVER_ERROR,"作者信息创建失败");
            }
        }
        // 修改ap_user中 flag值，改为自媒体用户
        apUser.setFlag((short)1);
        apUserMapper.updateById(apUser);
//        System.out.println(1/0); // 制造异常
//        if (!IdCardUtils.checkIdCardInfo(userRealname.getName(),userRealname.getIdno())) {
//            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"姓名和身份证号认证不通过");
//        }
        return ResponseResult.okResult();
    }
    @Autowired
    ArticleFeign articleFeign;
    private ResponseResult createAuthor(ApUser apUser, WmUser wmUser) {
        // 根据apUserId 查询作者信息
        ApAuthor author = articleFeign.findByUserId(apUser.getId());
        if(author!=null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"对应的作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        return articleFeign.save(author);
    }

    @Autowired
    WemediaFeign wemediaFeign;
    private WmUser createWmUser(ApUser apUser) {
        // 根据用户名 查询 对应的自媒体信息是否存在
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if(wmUser != null){
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体用户已经存在");
        }
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        return wemediaFeign.save(wmUser);
    }
}
